﻿using System.Web.Mvc;
using Liber.WEB;
using System.Web.UI;
using System;
using System.Web.Caching;
using Liber;

namespace SoBusiness.Controllers
{
    [NoSession]
    public class RegisterController : LiberController
    {
        [HttpPost]
        public JsonResult BindOpenAcnt()
        {
            string acnt = Request.Params["acnt"];
            string pass = Request.Params["pass"];
            string openId = Request.Params["openid"];
            string openSrc = Request.Params["opensrc"];
            string openHeadImg = Request.Params["openheadimg"];
            string openname = Request.Params.TryGet("openname");
            if (acnt == "")
            {
                return Json(FnResult.Failure("RegisterController", "RequiredArgs").SetError("acnt", "acnt is empty"));
            }

            var rtn = API.NoauthorRequest("RegisterApp@BindOpenAcnt")
                        .Set("acnt", acnt)
                        .Set("pass", pass)
                        .Set("openid", openId)
                        .Set("opensrc", openSrc)
                        .Set("openname",openname)
                        .Set("openheadimg", openHeadImg)
                        .WaitResult();
            if (rtn.IsPositive)
            {
                var sn = API.GetOpenSession(openId, openSrc);
                if (sn.IsPositive)
                {
                    SoBizController.SetLoginStatus(HttpContext, sn.Data);
                }
            }
            return Json(rtn);
        }

        [HttpPost]
        public JsonResult CreateAcnt(string phone, string captcha,string pass,string name,string src,string openname,string openid,string headimg)
        {
            if (Session["phone"]==null||Session["phone"].ToString() != phone)
            {
                return Json(FnResult.Failure("RegisterController", "UnmatchPhone"));
            }
            else if (HttpContext.Cache[phone + "captcha"] == null || HttpContext.Cache[phone + "captcha"].ToString() != captcha)
            {
                return Json(FnResult.Failure("RegisterController", "UnmatchCaptcha"));
            }
            else
            {
                if (string.IsNullOrWhiteSpace(pass))
                {
                    return Json(FnResult.Failure("RegisterController", "RequiredArgs").SetError("pass", "pass is empty"));
                }
                var rtn = API.NoauthorRequest("RegisterApp@CreateAcnt")
                           .Set("acnt", phone)
                           .Set("name", string.IsNullOrWhiteSpace(name)?phone:name)
                           .Set("phone",phone)
                           .Set("headimg", string.IsNullOrWhiteSpace(headimg)?"/UserFile/DefaultUserLogo.png":headimg)
                           .Set("pass", pass)
                           .Set("openid", openid)
                           .Set("opensrc", src)
                           .Set("openname",openname)
                           .Set("openheadimg", headimg)
                           .WaitResult();
                if (rtn.IsPositive)
                {
                    SoBizController.SetLoginStatus(HttpContext, rtn.Data);
                }
                return Json(rtn);
            }
        }

        public JsonResult SendCaptcha(string phone,string forwhat,string challenge,string validate, string seccode)
        {
            //判断是否通过微信客户端访问
            if (TLB2BController.IsWxLogined(HttpContext) == ""&&!IsLogined(HttpContext))
            {
                //检查图形验证码
                
                //api key: a41196c785c36ae86d65046ac176e6aa
                //https://captcha.luosimao.com/api/site_verify
                var iv = WebHelper.GetResponseFrom(@"https://captcha.luosimao.com/api/site_verify?api_key=a41196c785c36ae86d65046ac176e6aa&response=" + validate);
                if (iv == null)
                {
                    return Json(FnResult.Failure("RegisterController", "BadImageValidator").SetError("error", "no response from captcha_luosimao"));
                }
                string msg = iv.ReadToStr();
                if (msg.IndexOf("success") > 0)
                {
                    
                }
                else
                {
                    return Json(FnResult.Failure("RegisterController", "BadImageValidator").SetError("error", iv.ReadToStr()));
                }
            }

            if (HttpContext.Cache[phone + "lastSend"] != null)
            {
                return Json(FnResult.Failure("RegisterController", "ShortInterval"));
            }
            //记录每个电话号码最后一次发送验证码的时间，间隔不能少于1分钟
            HttpContext.Cache.Add(phone + "lastSend", DateTime.Now, null, DateTime.Now.AddMinutes(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null);

            if (HttpContext.Cache[phone + "maxTimes"] != null)
            {
                short sendTimes = (short)HttpContext.Cache[phone + "maxTimes"];
                if (sendTimes > 5)
                {
                    //TODO:记录这些每天发送超过5次的手机号、mac地址
                    return Json(FnResult.Failure("RegisterController", "MaxTimes"));
                }
                else
                {
                    sendTimes += 1;
                    HttpContext.Cache.Remove(phone + "maxTimes");
                    HttpContext.Cache.Add(phone + "maxTimes", sendTimes,null,DateTime.Today.AddDays(1),Cache.NoSlidingExpiration,CacheItemPriority.Default,null);
                }
            }
            else
            {
                short sendTimes = 1;
                HttpContext.Cache.Add(phone + "maxTimes", sendTimes, null, DateTime.Today.AddDays(1), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
            }

            //发送验证码
            var rsult = API.NoauthorRequest("RegisterApp@SendCpatcha")
                           .Set("phone", phone)
                           .Set("forwhat", forwhat)
                           .WaitResult();

            if (rsult.IsPositive)
            {
                //保存当前会话对应的电话号码和验证码，验证码5分钟内有效
                Session.Remove("phone");
                Session.Add("phone", phone);
                HttpContext.Cache.Remove(phone+"captcha");
                HttpContext.Cache.Add(phone+"captcha", rsult.Data["captcha"], null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                rsult.Data.Remove("captcha");
            }
            return Json(rsult);
        }

        //public JsonResult GetValidator()
        //{
        //    GeetestLib geetest = new GeetestLib("38fbf0b023d6bb97f518471d3dc39c2a", "ca1113b4c9f863e47b03d13b88049651");
        //    Byte gtServerStatus = geetest.preProcess();
        //    Session[GeetestLib.gtServerStatusSessionKey] = gtServerStatus;
        //    var v= geetest.getResponseStr();
        //    return Json(FnResult.Sucess(v));
        //}

        public JsonResult CheckCaptcha(string phone,string captcha)
        {
            if (Session["phone"] == null || Session["phone"].ToString() != phone)
            {
                return Json(FnResult.Failure("RegisterController", "UnmatchPhone"));
            }
            else if (HttpContext.Cache[phone + "captcha"] == null || HttpContext.Cache[phone + "captcha"].ToString() != captcha)
            {
                return Json(FnResult.Failure("RegisterController", "UnmatchCaptcha"));
            }
            else
            {
                return Json(FnResult.Sucess());
            }
        }

        public JsonResult ResetPwd(string phone,string captcha,string pass)
        {
            if (Session["phone"] == null || Session["phone"].ToString() != phone)
            {
                return Json(FnResult.Failure("RegisterController", "UnmatchPhone"));
            }
            else if (HttpContext.Cache[phone + "captcha"] == null || HttpContext.Cache[phone + "captcha"].ToString() != captcha)
            {
                return Json(FnResult.Failure("RegisterController", "UnmatchCaptcha"));
            }
            else
            {
                return Json(API.NoauthorRequest("RegisterApp@ResetPwd")
                                .Set("phone", phone)
                                .Set("newpass", pass)
                                .WaitResult());
            }
        }

    }
}